Variables

<-- Prev --------- Contents --------- Next -->

Variables are short-term memory for your program. If you have a number or word you would like to have your program remember for later use, variables are what you need. You can think of them as storage for information in your program.

Data Types

There are several different types of information that can be stored in a variable. However, you must tell the computer what type of information each variable will hold before you use it. Below is a table explaining some of the most common types of variables.
Variable type
What it stores
String
Sentences, words, letters
char
single letter, single digit (char stands for character)
int
whole numbers (including negatives and zero)
float
decimal numbers
bool
true or false

Naming Your Variables

In order to distinguish between variables, you must give each variable a unique name. A variable may be named anything you like - with a few restrictions:
  • A variable may not have the same name as a C# keyword. For example, you may NOT name a variable "int" or "main".
  • A variable may not have the same name as another variable. You may have only one variable named "x".
  • A variable name may only contain letters (upper or lower case), numbers, or underscores ("_"). No other characters are permitted. No spaces!
  • A variable name may not start with a number.
A few examples of valid variable names are:
  • x
  • fred
  • user_name
  • userName
  • user_1
While this obviously gives you a lot of freedom in naming your variables, remember that it will be very difficult to read your own code if you do not name your variables wisely. For example, you would not want to have 15 variables, all named x1,x2,x3, etc, if they are used for different purposes - they would be impossible to keep straight in your head! Also, avoid excessively long names like "supercalifragilisticexpialadocious". They aren't fun to type more than once. Keep your variable names short, but descriptive. Good examples are:
  • x_coord
  • first_name, last_name
  • distance

Example


Let's look back at the Hello World program. We will have the program prompt you for your name, so that the computer can say "Hello <insert your name here>".

Declaring Variables


In order to use a variable, we must first declare it. Declaring a variable is where you tell the program what type of variable you need (int, string, etc), and what you want to name it. Additionally, you may choose to give the variable an initial value (variable initialization) but this is optional.

Here is an example variable declaration (and initialization).
 string username = "nothing yet";
This tells the computer "Hey, I want to create a string variable called username" and also sets the variable to be equal to "nothing yet". Recall that string variables store letters and words. You could also declare the variable without setting it equal to anything (aka without initializing it), like this:
string username;
This creates the variable, but leaves it completely empty.

Storing Information in Variables


In order to set this variable to use something you type in, we are going to use System.Console.ReadLine(); This reads in a line from the console, and stores the results in the variable named "username".
username = System.Console.ReadLine();

Using the information you stored


Next, we'll want to use the name we just read in from the console. Go ahead and create a project called HelloName.

First, let's talk about two important points when working with strings.

String Concatenation

Before we get too far we need to discuss string concatenation. This is fancy programming speak for joining 2 strings together. In C# string concatenation is done using the + symbol. It's just like adding two strings together!

Quotes

Quotes tell the computer that something you have written is text, and you want it treated as text, as opposed to being code. Thus, things in quotations are treated as strings, regardless of what's in them.

Now, let's use concatenation, along with proper use of quotations, to print back the username in our program. Below are the lines we will be adding. Don't forget the space at the end of Hello!
System.Console.WriteLine("Hello " + username);
System.Console.ReadLine();
Just like in our HelloWorld program, the WriteLine() line prints to the screen. This time, however, we used concatenation inside of the parenthesis to append the username to the end of the sentence. Notice that "Hello " is in quotations, but username is not. This is because "Hello " is simply text that we want printed; username is a variable name storing text.
(Note: The extra System.Console.ReadLine(); keeps the screen open so that you can see the results.)

Now hit play at the top of the screen. A blank screen will appear.
Type your name in the screen and press Enter.
You should see a screen similar to the one below.

HelloFred.jpg
This is your first use of variables.



Pop Quiz:
If we were to change the WriteLine() code to read:
System.Console.WriteLine("Hello " + "username");
And the user typed John as input, what would be the output of our program?
Hello username
Hello "username"
Hello John
Hello "John"



Using Numbers


Now lets try making a simple calculator that will add 2 numbers.

Go ahead and create a new project called Calculator.

First you need to declare the variables
int numberOne = 0;
int numberTwo = 0;
int Added = 0;
 
Note that they are integer variables.

Second we will want to prompt the user for the two numbers to add. We can do this by writing a line that requests the user to enter the first number below, and then prompt for a second number after that.
system.Console.WriteLine("First Number");
numberOne = system.Console.Readline();
system.Console.WriteLine("Second Number");
numberTwo = system.Console.Readline();
 
Now that we have the information from the user we can add it together.
Added = numberOne + numberTwo;
And Print the Results
System.Console.WriteLine(numberOne + " + " + numberTwo + " = " + Added);
system.Console.ReadLine();
 
Press Play.

Uh Oh it doesn't work!!!

Why Not?

Lets look back at the Data Types. Remember when we said that strings were for words and int was for numbers? Well when you type in information into the console it is seen as TEXT; even if you are pressing the number keys, the computer sees it all as text. So we need to convert it from text to numbers.
Luckily C# has some built-in code that we can call on to do this. It is:
int32.parse( string );
You will put the text that you want to convert to an integer into the parentheses, in place of "string". Remember, if you are putting a variable name in the parentheses, it does NOT need quotes. If it is a normal text, it DOES.

String Conversion
Add the int32.parse to your program and it should look like this.
system.Console.WriteLine("First Number");
numberOne = int32.parse(system.Console.Readline());
system.Console.WriteLine("Second Number");
numberTwo = int32.parse(system.Console.Readline());

So the whole program should look like this and work!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            int numberOne = 0;
            int numberTwo = 0;
            int Added = 0;
 
            System.Console.WriteLine("First Number");
            numberOne = Int32.Parse(System.Console.ReadLine());
            System.Console.WriteLine("Second Number");
            numberTwo = Int32.Parse(System.Console.ReadLine());
 
            Added = numberOne + numberTwo;
 
            System.Console.WriteLine(numberOne + " + " + numberTwo + " = " + Added);
            System.Console.ReadLine();
 
        }
    }
}
 

Your screen should look something like this.

adder.jpg

Hooray!

Variable Scope


One more important thing you need to know is called the scope of your variables. The scope of the variable defines what parts of your code can access the variables you define. Some variables can only be accessed by code in their local block, while some can be accessed by most program. But how do you know which are which? In C#, this is decided by where you declare the variable.

Suppose you define a variable outside of your main (above it, for example), like this:
int my_number;
 
static void Main()
{
}
In this case, the variable my_number is contained by the "class Program" braces. This means that it can be accessed anywhere within the Program block.

Suppose we made another variable, like this:
static void Main()
{
  int my_number_2;
}
In this case, my_number_2 could only be accessed from within the Main() function. This may not seem like a big deal now (because all of our code has been in the Main so far), but later on we will have code outside of the Main- and it would not be able to use my_number_2!

But things get even more specific than that- Suppose we made a variable inside of an if-statement block:
static void Main()
{
  int x = 0;
  if ( x == 0 )
  {
     int my_number_3 = 0;
  }
 
  System.Console.WriteLine(my_number_3);
}
The above code would generate an error. Why? Because we declared 'my_number_3' inside of the if-block... so it can only be accessed within the if-block. After the if-block ends, my_number_3 no longer exists! If we wanted to use my_number_3 inside of the if-block, but keep it around afterwards, then we would have to declare it beforehand, like this:
static void Main()
{
  int x = 0;
  int my_number_3;
  if ( x == 0 )
  {
     my_number_3 = 0;
  }
 
  System.Console.WriteLine(my_number_3);
}
Keep this in mind as you work. Any time you have a set of braces ({...}), any variables that you declare within them are local to that set of braces - and will disappear when the braces end.

<-- Prev --------- Contents --------- Next -->